package com.im.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.ListUtils;

import com.im.MDA;
import com.im.service.dto.BaseException;
import com.im.service.dto.FundPlanStatic;
import com.im.service.dto.PageQuery;
import com.im.service.dto.PlanDeclareSet;
import com.im.service.dto.Staff;
import com.im.service.fundPlan.smo.IFundPlanManageOperSMO;
import com.im.service.fundPlan.smo.IFundPlanManageQuerySMO;
import com.im.util.JsonUtil;
import com.im.util.ReturnsUtil;
import com.im.util.StringUtil;
import com.im.viewmodel.fundPlan.FundPlanDeclareSetAddReqVo;
import com.im.viewmodel.fundPlan.FundPlanListRespVo;
import com.im.viewmodel.fundPlan.FundPlanRespVo;

import net.sf.json.JSONObject;

/**
 * 资金计划管理后端服务.
 * @author xuwenbo
 *
 */
@RestController
@RequestMapping("/fundPlanService")
public class FundPlanService {
	
	private static final Logger logger = LogManager.getLogger(FundPlanService.class);
	
	@Autowired
	private IFundPlanManageOperSMO fundPlanManageOperSMO;
	
	@Autowired
	private IFundPlanManageQuerySMO fundPlanManageQuerySMO;
	
	
	/**
	 *
	 *  资金计划申报---新增
	 * @param
	 * @return
	 * @throws Exception
	 */
//	@PostMapping(value = "/addFundPlanDeclareSet")
	@Deprecated
	public String addFundPlanDeclareSet(@Valid@RequestBody FundPlanDeclareSetAddReqVo addReqVo,BindingResult bindingResult,HttpServletRequest request){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", addReqVo.toString());
		}
		try {
			if (bindingResult.hasErrors()){
				return ReturnsUtil.returnFailure(bindingResult.getFieldError().getDefaultMessage());
		    }
			String errorMsg = fundPlanManageOperSMO.addFundPlanDeclareSet(addReqVo,request);
			if(!"".equals(errorMsg)){
				return ReturnsUtil.returnFailure(errorMsg);
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	
	/**
	 *
	 * 资金计划申报---新增
	 * 
	 * @param jsonStr
	 *            入参
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/addFundPlanDeclareSet")
	public String addFundPlanDeclareSet(HttpServletRequest request,@RequestBody String jsonStr) throws Exception {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", jsonStr);
		}
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("新增资金计划申报设置请求json入参为空，请核查数据!");
			}
			HttpSession session = request.getSession();
			Staff staff = (Staff) session.getAttribute("loginedStaff");
			String result = fundPlanManageOperSMO.addFundPlanDeclareSet(jsonStr, staff);
			JSONObject jsonObj = JSONObject.fromObject(result);
			String resultCode = JsonUtil.getStringFromJSON(jsonObj, "resultCode", "");
			if (MDA.RESULT_SUCCESS.equals(resultCode)) {
				return result;
			} else {
				return ReturnsUtil.returnFailure(JsonUtil.obtainValueFromJsonObject(result, "message"));
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}

	/**
	 *
	 * 修改投资计划申报设置
	 * 
	 * @param jsonStr
	 *            入参
	 * @return  addFundPlanDeclareSet
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateFundPlanDeclareSet", method = RequestMethod.POST)
	public String updateFundPlanDeclareSet(@RequestBody String jsonStr) throws Exception {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求json入参为空，请核查数据!");
			}
			fundPlanManageOperSMO.updateFundPlanDeclareSet(jsonStr);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();

		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	/**
	 * 资金计划申报设置列表查询
	 * 
	 * @param inJson
	 * @return
	 */
	@RequestMapping(value = "/queryFundPlanSetList", method = RequestMethod.POST)
	@ResponseBody
	public String queryFundPlanSetList(@RequestBody String inJson) {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", inJson);
		}
		if (inJson == null || inJson.length() <= 0) {
			throw new BaseException("请求json入参为空，请核查数据!");
		}
		try {
			PageQuery<PlanDeclareSet> planDeclareSets = fundPlanManageQuerySMO.queryFundPlanSetList(inJson);
			return ReturnsUtil.returnSuccess(planDeclareSets).toString();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ReturnsUtil.returnException("查询资金计划申报设置失败！", e).toString();
		}
	}

	/**
	 * 资金计划申报设置详情查询
	 * 
	 * @param inJson
	 * @return
	 */
	@RequestMapping(value = "/queryFundPlanSetDetail", method = RequestMethod.POST)
	@ResponseBody
	public String queryFundPlanSetDetail(@RequestBody String inJson) {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", inJson);
		}
		try {
			String declareSetId = JsonUtil.obtainValueFromJsonObject(inJson, "declareSetId");
			PlanDeclareSet declareSet = new PlanDeclareSet();
			declareSet.setDeclareSetId(declareSetId);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("declareSet", declareSet);
			PlanDeclareSet planDeclareSet = fundPlanManageQuerySMO.queryFundPlanSetDetail(paramMap);
			return ReturnsUtil.returnSuccess(planDeclareSet).toString();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ReturnsUtil.returnException("查询资金计划申报设置失败！", e).toString();
		}
	}
	
	
	/**
	 * 
	 * 1.资金计划填报列表查询. 
	 * 2.资金计划详情   fundPlanId
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryFundPlanList")
	public String queryFundPlanList(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}
		
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			List<Integer> statusList=new  ArrayList<Integer>();
			statusList.add(MDA.FUND_PLAN_STATUS_CD_WRITE);
			statusList.add(MDA.FUND_PLAN_STATUS_CD_WAIT);
			statusList.add(MDA.FUND_PLAN_STATUS_CD_FIR);
			statusList.add(MDA.FUND_PLAN_STATUS_CD_FIR_REFUSE);
			statusList.add(MDA.FUND_PLAN_STATUS_CD_PASS);
			PageQuery<FundPlanRespVo> result = fundPlanManageQuerySMO.queryFundPlanListNew(jsonStr, statusList);
			
			return ReturnsUtil.returnSuccess(result).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	/**
	 *
	 * 资金计划填报---新增
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/addFundPlan")
	public String addFundPlan(@RequestBody FundPlanListRespVo reqVo) {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", reqVo.toString());
		}
		try {
			if (reqVo == null) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			String errorMsg = fundPlanManageOperSMO.addFundPlan(reqVo);
			if(!"".equals(errorMsg)){
				return ReturnsUtil.returnFailure(errorMsg);
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}

	/**
	 *
	 * 资金计划填报---修改
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/updateFundPlan")
	public String updateFundPlan(@RequestBody FundPlanListRespVo reqVo){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", reqVo.toString());
		}
		try {
			if (reqVo == null || StringUtil.isEmpty(reqVo.getFundPlanId())) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			fundPlanManageOperSMO.updateFundPlan(reqVo);
			
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	/**
	 *
	 *  资金计划填报---删除
	 *  
	 *  该功能调整为：删除时，清楚填报所修改的内容，状态修改为 20：开放填报
	 * @param
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/deleteFundPlan")
	public String deleteFundPlan(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", jsonStr);
		}
		try {
			FundPlanListRespVo reqVo = JsonUtil.jsonToBean(jsonStr, FundPlanListRespVo.class);
			if (reqVo == null || StringUtil.isEmpty(reqVo.getFundPlanId())) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			fundPlanManageOperSMO.deleteFundPlan(reqVo);
			
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	/**
	 * 
	 * 1.资金计划初审列表查询. 
	 * 2.资金计划初审详情    fundPlanId
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAuditFundPlanList")
	public String queryAuditFundPlanList(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}
		
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			List<Integer> statusList=new  ArrayList<Integer>();
			statusList.add(MDA.FUND_PLAN_STATUS_CD_WAIT);
			PageQuery<FundPlanRespVo> result = fundPlanManageQuerySMO.queryFundPlanListNew(jsonStr, statusList);
			
			return ReturnsUtil.returnSuccess(result).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	/**
	 *
	 *  1.资金计划审核
	 *  2.资金计划批复与下达
	 * @param
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/auditFundPlan")
	public String auditFundPlan(@RequestBody FundPlanListRespVo reqVo){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", reqVo.toString());
		}
		try {
			if (reqVo == null || (StringUtil.isEmpty(reqVo.getFundPlanId())
					&& (reqVo.getFundPlanIds() == null || reqVo.getFundPlanIds().size() == 0))) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			fundPlanManageOperSMO.auditFundPlan(reqVo);
			
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}

	/**
	 *
	 * 1.资金计划审核 2.资金计划批复与下达
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/batchAuditFundPlan")
	public String batchAuditFundPlan(@RequestBody FundPlanListRespVo reqVo) {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参:{}", reqVo.toString());
		}
		try {
			if (reqVo == null
					|| (StringUtil.isEmpty(reqVo.getFundPlanId()) && ListUtils.isEmpty(reqVo.getFundPlanIds()))) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			fundPlanManageOperSMO.batchAuditFundPlan(reqVo);

			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	
	/**
	 * 
	 * 1.资金计划批复与下达 列表查询. 
	 * 2.资金计划批复与下达详情    fundPlanId
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryReplyFundPlanList")
	public String queryReplyFundPlanList(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}
		
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			List<Integer> statusList=new  ArrayList<Integer>();
			statusList.add(MDA.FUND_PLAN_STATUS_CD_FIR);
			PageQuery<FundPlanListRespVo> result = fundPlanManageQuerySMO.queryFundPlanList(jsonStr,statusList);
			
			return ReturnsUtil.returnSuccess(result).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	/**
	 *
	 * 资金计划统计
	 * 
	 * @param jsonStr
	 *            入参
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/queryFundPlanStaticList")
	public String queryFundPlanStaticList(@RequestBody String jsonStr) throws Exception {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求json入参为空，请核查数据!");
			}
			PageQuery<FundPlanStatic> result = fundPlanManageQuerySMO.queryFundPlanStaticList(jsonStr);
			return ReturnsUtil.returnSuccess(result).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}
	
	
//	/**
//	 * 保存资金计划申报设置
//	 * @param jsonStr
//	 * @return
//	 */
//	@RequestMapping(value = "/savePlandDeclareSet")
//	public String savePlandDeclareSet(@RequestBody String jsonStr){
//		JSONObject ret = new JSONObject();
//		ret.put("resultCode", "0");
//		ret.put("resultMsg", "成功");
//		try{
//			
//			fundPlanManageOperSMO.saveFundPlanSetInfo(jsonStr);
//			
//		} catch (Exception e){
//			return ReturnsUtil.returnFailure(e.getMessage());
//		}
//		return ReturnsUtil.returnSuccess(ret.toString()).toString();
//	}
//	
//	
//	/**
//	 * 保存资金计划申报设置
//	 * @param jsonStr
//	 * @return
//	 */
//	@RequestMapping(value = "/saveFundPlan")
//	public String saveFundPlan(@RequestBody String jsonStr){
//		JSONObject ret = new JSONObject();
//		ret.put("resultCode", "0");
//		ret.put("resultMsg", "成功");
//		try{
//			fundPlanOperSMO.saveFundPlanInfo(jsonStr);
//			
//		} catch (Exception e){
//			return ReturnsUtil.returnFailure(e.getMessage());
//		}
//		return ReturnsUtil.returnSuccess(ret.toString()).toString();
//	}


	@RequestMapping(value = "/updateFundPlanDeclareSetByCondition", method = RequestMethod.POST)
	public String updateFundPlanDeclareSetByCondition(@RequestBody String jsonStr) throws Exception {
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}
		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求json入参为空，请核查数据!");
			}
			fundPlanManageOperSMO.updateFundPlanDeclareSetByCondition(jsonStr);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();

		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}


	/**
	 * 查询资金计划批复数据 新接口
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping(value = "/queryShFundPlanListNew")
	public String queryShFundPlanListNew(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}

		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			List<Integer> statusList=new  ArrayList<Integer>();
			statusList.add(MDA.FUND_PLAN_STATUS_CD_FIR);
			PageQuery<FundPlanRespVo> result = fundPlanManageQuerySMO.queryFundPlanListNew(jsonStr,statusList);

			return ReturnsUtil.returnSuccess(result).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}


	/**
	 * 资金计划审批绿色通道
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping(value = "/addFundPlanGreen")
	public String addFundPlanGreen(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}

		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			String string = fundPlanManageOperSMO.addFundPlanGreen(jsonStr);
			return ReturnsUtil.returnSuccess(string).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}


	/**
	 * 资金计划审批绿色通道
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping(value = "/queryFundPlanListForGreen")
	public String queryFundPlanListForGreen(@RequestBody String jsonStr){
		if (logger.isInfoEnabled()) {
			logger.info("请求入参json:{}", jsonStr);
		}

		try {
			if (jsonStr == null || jsonStr.length() <= 0) {
				throw new BaseException("请求入参为空，请核查数据!");
			}
			FundPlanRespVo fundPlanRespVo = fundPlanManageQuerySMO.queryFundPlanListForGreen(jsonStr);

			return ReturnsUtil.returnSuccess(fundPlanRespVo).toString();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		}
	}

}
